package com.wsd.action.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionContext;
import com.wsd.action.BaseAction;
import com.wsd.bean.Category;
import com.wsd.bean.Message;
import com.wsd.bean.Price;
import com.wsd.bean.ProductComment;
import com.wsd.bean.Products;
import com.wsd.service.CategoryService;
import com.wsd.service.ProductService;
import com.wsd.util.FileUtil;
import com.wsd.util.PagingBuilder;

public class ProductAction extends BaseAction {
	private ProductService productService;
	private CategoryService categoryService;
	private Products product;
	private Category category;
	private Price price1;
	private Price price2;
	private Price price3;
	private File upload;
	private String uploadContentType;//上传文件类型的属性
	private String uploadFileName;//上传文件名属性
	private String savePath;//文件保存路径
	private String filePath;//通过传进来的参数 构造出文件在服务器上的路径
	private String text;
	private boolean search;//搜索标志
	private int start;
	private int limit;
	private int total;
	private String key;
	private int[] ids;
	private Short model;
	private int pid;
	private int cid;//评论id
	private int page = 1;
	@JSON(serialize = false)
	public ProductService getProductService() {
		return productService;
	}
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
	@JSON(serialize = false)
	public CategoryService getCategoryService() {
		return categoryService;
	}
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
	@JSON(serialize = false)
	public Products getProduct() {
		return product;
	}
	public void setProduct(Products product) {
		this.product = product;
	}
	@JSON(serialize = false)
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	@JSON(serialize = false)
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	@JSON(serialize = false)
	public Price getPrice1() {
		return price1;
	}
	public void setPrice1(Price price1) {
		this.price1 = price1;
	}
	@JSON(serialize = false)
	public Price getPrice2() {
		return price2;
	}
	public void setPrice2(Price price2) {
		this.price2 = price2;
	}
	@JSON(serialize = false)
	public Price getPrice3() {
		return price3;
	}
	public void setPrice3(Price price3) {
		this.price3 = price3;
	}
	@JSON(serialize = false)
	public String getUploadFileName() {
		return UUID.randomUUID().toString();
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	@JSON(serialize = false)
	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	@JSON(serialize = false)
	public String getFilePath() {
		return getSavePath() + "/" + getUploadFileName();
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	
	@JSON(serialize = false)
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	@JSON(serialize = false)
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	@JSON(serialize = false)
	public boolean isSearch() {
		return search;
	}
	public void setSearch(boolean search) {
		this.search = search;
	}
	
	@JSON(serialize = false)
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	@JSON(serialize = false)
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	@JSON(serialize = false)
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	@JSON(serialize = false)
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	@JSON(serialize = false)
	public int[] getIds() {
		return ids;
	}
	public void setIds(int[] ids) {
		this.ids = ids;
	}
	@JSON(serialize = false)
	public Short getModel() {
		return model;
	}
	public void setModel(Short model) {
		this.model = model;
	}
	@JSON(serialize = false)
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	@JSON(serialize = false)
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	@JSON(serialize = false)
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public String uploadImage() throws IOException{
		
		String msg = "导入成功";
		success = true;
		if(upload.length() > 1024*1024*10){
			msg = "容量超过限制";
			success = false;
		}else {
			File newFile = FileUtil.buildFile(getFilePath(), FileUtil.getFileType(uploadFileName));
			
			//System.out.println(newFile.getAbsolutePath());
			System.out.println(text);
		}
				
		
		String outPut = "{success:" + success +",msg:'" + msg + "'}";
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		
		out.print(outPut);
		out.close();
		return null; 
	}
	
	/**
	 * 添加商品
	 * @return
	 * @throws IOException 
	 */
	public String addProduct() throws IOException{
		String msg = "";
		if(upload.length() > 1024*1024*10){
			msg = "图片容量超过限制";
			success = false;
		}else {
			File newFile = FileUtil.buildFile(getFilePath(), FileUtil.getFileType(uploadFileName));
			upload(newFile);
			Set<Price> priceSet = new HashSet<Price>();
			price1.setULevel(1);
			price2.setULevel(2);
			price3.setULevel(3);
			priceSet.add(price1);
			price1.setProducts(product);
			priceSet.add(price2);
			price2.setProducts(product);
			priceSet.add(price3);
			price3.setProducts(product);
			
			product.setPrices(priceSet);
			product.setCategory(category);
			product.setImage(newFile.getName());
			try{
				productService.save(product);
			}catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(newFile.getAbsolutePath());
			System.out.println(newFile.getName());
			System.out.println(text);
			success = true;
		}
				
		String outPut = "{success:" + success +",msg:'" + msg + "'}";
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		
		out.print(outPut);
		out.close();
		return null;
	}
	/**
	 * 搜索
	 * @return
	 */
	public String search(){
		List<Products> products  = null;
		if(search){
			System.out.println(key);
			products = productService.searchProducts(start/limit + 1, limit, key);
			total = productService.getTotalPages(limit, key);
			System.out.println("total:::" + total);
		}else{
			//category = categoryService.findById(category.getCId());
			//category = categoryService.findById(39);
			if(null == category.getCId() || 0 == category.getCId())
				category.setCId(1);
		    products = productService.categoryProducts(start/limit + 1, limit, category.getCId());
			total = productService.getProductCount(category.getCId());
			
		}
		processProducts(products);
		result.put("total", total);
		result.put("products", products);
		return AJAX;
	}
	
	/**
	 * @param products
	 */
	private void processProducts(List<Products> products) {
		category = null;
		if(products.size() > 0){
			Products product = products.get(0);
			category = new Category();
			category.setCId(product.getPId());
			category.setCName(product.getCategory().getCName());
		}
		for(Products product : products){
			//防止hibernate延迟加载和json的冲突
			category = new Category();
			category.setCName(product.getCategory().getCName());
			category.setCId(product.getCategory().getCId());
			product.setCategory(category);
			product.setProductRanks(null);
			//product.setProductComments(null);
		}
	}
	public String delete(){
		productService.deleteProduct(ids);
		return AJAX;
	}
	
	public String update() throws IOException{
		String msg = "";
		Products preProduct = productService.findById(product.getPId());
		
		BeanUtils.copyProperties(product, preProduct, new String[]{"category","image","prices"});
		if(upload != null){
			//没上传图片默认用旧图片
			if(upload.length() > 1024*1024*10){
				msg = "图片容量超过限制";
				success = false;
			}else {
				File newFile = FileUtil.buildFile(getFilePath(), FileUtil.getFileType(uploadFileName));
				upload(newFile);
				preProduct.setImage(newFile.getName());
				success = true;
			}
		}
		try{
			
			addPrice(preProduct);
			
			productService.update(preProduct);
		}catch(Exception e){
			e.printStackTrace();
		}
		String outPut = "{success:" + success +",msg:'" + msg + "'}";	
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		
		out.print(outPut);
		out.close();
		
		return AJAX;
	}
	public String allComments(){
		List<ProductComment> productComments = productService.findAllComments((page - 1)*5,5);
		String pageStr = PagingBuilder.build("/wsd/admin/product_allComments.action?page=@page@", page, 10, (productService.findAllCommentsCount() - 1)/5 + 1);
		ActionContext.getContext().put("productComments", productComments);
		ActionContext.getContext().put("pageStr", pageStr);
		ActionContext.getContext().put("curPage", page);
		return "all";
	}
	
	/**
	 * 上传文件
	 * @return
	 */
	private boolean upload(File uploadFile){
		FileOutputStream fos = null;
		FileInputStream fis = null ;
		try {
			//uploadFile.mkdirs();
			fos = new FileOutputStream(uploadFile);
			fis = new FileInputStream(getUpload());
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = fis.read(buffer)) > 0){
				fos.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally{
			try {
				if(fos != null){
					fos.close();
				}
				if(fis != null){
					fis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return true;
	}
	public String saveRank(){
		productService.saveRank(ids,model);
		return AJAX;
	}
	/**
	 * 返回榜单商品
	 * @return
	 */
	public String rankProducts(){
		List<Products> products = null;
		products = productService.rankProducts(model,start,limit);
		total = productService.rankProductsCount(model);
		if(products != null){
			processProducts(products);
		}
		result.put("products", products);
		result.put("total", total);
		return AJAX;
	}
	
	public String removRank(){
		productService.deleteRank(ids,model);
		return AJAX;
	}
	/**
	 * 显示商品留言
	 * @return
	 */
	public String comments(){
		ActionContext.getContext().put("product", productService.findById(pid));
		return "comments";
	}
	/**
	 * 删除商品评论
	 * @return
	 */
	public String deleteComments(){
		productService.deleteComment(cid);
		ActionContext.getContext().put("pid", pid);
		return "delete";
	}
	//评论管理页面用到
	public String deleteComment(){
		productService.deleteComment(cid);
		ActionContext.getContext().put("page", page);
		return "allComments";
	}
	private void addPrice(Products product){
		for (Iterator iter = product.getPrices().iterator(); iter.hasNext();) {
			Price price = (Price) iter.next();
			switch (price.getULevel()) {
			case 1:
				price.setPrice(price1.getPrice());
				break;
			case 2:
				price.setPrice(price2.getPrice());
				break;
			case 3:
				price.setPrice(price3.getPrice());
				break;
			default:
				break;
			}
			
		}
	}
	public String detail(){
		Products product = productService.findById(pid);
		ActionContext.getContext().put("product", product);
		return "detail";
	}
	

}
